package com.greenzebras.geocache;

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.greenzebras.geocache.cachedata.Cache;
import com.greenzebras.geocache.cachedata.CacheCoordinate;
import com.greenzebras.geocache.cachedata.CacheType;
import com.greenzebras.geocache.constant.GeocacheConstants;
import com.greenzebras.geocache.datastore.GeocacheCacheManagementRequestResponseListener;
import com.greenzebras.geocache.datastore.persistence.GeocacheDataService;

public class GeocacheCreateActivity extends Activity implements
		GeocacheCacheManagementRequestResponseListener {

	EditText cacheNameTextView = null;
	private String latitude = null;
	private String longitude = null;
	// private String address = null;
	private CacheType cacheType = CacheType.TRADITIONAL;

	Button saveButton;
	Button cancelButton;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create);

		((TextView) findViewById(R.id.activity_title)).setText(R.string.create);

		latitude = (String) getIntent().getExtras().get(
				"latitudeForCacheCreate");

		longitude = (String) getIntent().getExtras().get(
				"longitudeForCacheCreate");

		// address = (String)
		// getIntent().getExtras().get("addressForCacheCreate");

		if (null == latitude || null == longitude) {
			Log.e(getClass().getName(), "Null Latitude and Longitude");
		} else {
			initializeAddressDetails();
			initializeButtons();
		}
		cacheNameValidate();
		populateCacheTypeSpinner();
	}

	private void initializeButtons() {
		setSaveButton();
		setCancelButton();
	}

	private void setSaveButton() {
		Button.OnClickListener addButtonOnClickListener = new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (createdFieldsValid()) {
					Cache cache = retrieveCacheToSave();
					createCache(cache);
				}
			}
		};

		saveButton = (Button) findViewById(R.id.commit_button);
		saveButton.setText(R.string.save_button);
		saveButton.setOnClickListener(addButtonOnClickListener);
	}

	private void setCancelButton() {

		Button.OnClickListener cancelButtonOnClickListener = new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				setResult(RESULT_OK);
				finish();
			}
		};
		cancelButton = (Button) findViewById(R.id.cancel_button);
		cancelButton.setText(R.string.cancel_button);
		cancelButton.setOnClickListener(cancelButtonOnClickListener);
	}

	private void createCache(Cache cache) {
		GeocacheDataService.INSTANCE.createCache(this, cache);
	}

	private void initializeAddressDetails() {
		TextView latitudeTextView = (TextView) findViewById(R.id.cache_latitude);
		latitudeTextView.setText(latitude);
		TextView longitudeTextView = (TextView) findViewById(R.id.cache_longitude);
		longitudeTextView.setText(longitude);
	}

	private Cache retrieveCacheToSave() {
		int lat = locationCoordinateToGeopointCoordinate(Double
				.parseDouble(latitude));
		int lng = locationCoordinateToGeopointCoordinate(Double
				.parseDouble(longitude));
		GeoPoint geopoint = new GeoPoint(lat, lng);

		CacheCoordinate cacheCoordinate = new CacheCoordinate();
		cacheCoordinate.setGeoPoint(geopoint);
		Cache cacheToSave = new Cache();
		cacheToSave.setCacheCoordinate(cacheCoordinate);

		EditText cacheNameTextView = (EditText) findViewById(R.id.cache_name);
		cacheToSave.setName(cacheNameTextView.getText().toString());

		EditText cacheDescriptionTextView = (EditText) findViewById(R.id.cache_description);
		cacheToSave.setDescription(cacheDescriptionTextView.getText()
				.toString());

		cacheToSave.setCacheType(cacheType);

		return cacheToSave;
	}

	private boolean validateNameTextField() {
		// name field is valid
		boolean isNameTextFieldIsValid = (cacheNameTextView.getText()
				.toString().length() >= GeocacheConstants.MINIMUM_NAME_LENGTH);
		if (!isNameTextFieldIsValid) {
			String errorString = getString(R.string.name_validation_error_string);
			ForegroundColorSpan fSpan = new ForegroundColorSpan(
					GeocacheConstants.FOREGROUND_COLOR);
			SpannableStringBuilder ssBuilder = new SpannableStringBuilder(
					errorString);
			ssBuilder.setSpan(fSpan, 0, errorString.length(), 0);
			cacheNameTextView.setError(ssBuilder);
		}

		return isNameTextFieldIsValid;
	}

	@Override
	public void processGeocacheCacheManagementRequestResponse(
			RequestStatus requestStatus, Cache cache) {
		if (requestStatus.equals(RequestStatus.SUCCESS)) {
			Toast.makeText(getApplicationContext(),
					getString(R.string.save_success_message), 5).show();
			setResult(RESULT_OK);
			finish();
		} else {
			Toast.makeText(getApplicationContext(),
					getString(R.string.save_error_message), 5).show();
		}

	}

	private int locationCoordinateToGeopointCoordinate(double locationCoordinate) {
		return (int) (locationCoordinate * GeocacheConstants.LOCATION_COORD_TO_GEOPOINT_COORD_MULTIPLIER);
	}

	private void populateCacheTypeSpinner() {
		ArrayAdapter<CacheType> cacheTypeArrayAdapter = new ArrayAdapter<CacheType>(
				this, android.R.layout.simple_spinner_item, CacheType.values());
		cacheTypeArrayAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		Spinner cacheTypeSpinner = ((Spinner) findViewById(R.id.cache_type_spinner));
		cacheTypeSpinner.setAdapter(cacheTypeArrayAdapter);
		cacheTypeSpinner
				.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> parent,
							View view, int position, long id) {
						cacheType = (CacheType) parent
								.getItemAtPosition(position);

					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub

					}
				});
	}

	private void cacheNameValidate() {
		// attach text change listener to the name field to enable validation
		cacheNameTextView = (EditText) findViewById(R.id.cache_name);
		cacheNameTextView.addTextChangedListener(new TextWatcher() {

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// empty implementation
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// empty implementation
			}

			public void afterTextChanged(Editable s) {
				validateNameTextField();
			}
		});
	}

	private boolean createdFieldsValid() {
		return validateNameTextField();
	}

}
